﻿using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QQ群成员获取.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace QQ群成员获取.Common
{
    /// <summary>
    /// 群信息管理
    /// </summary>
    public class GroupInfoManage
    {
        private string strCookie;
        private string strBkn;
        private int iCount=40;
        public int PageCount {
            get { return iCount; }
        }
        //获取当前页最大个数
        public int GetMaxCount(int iPage)
        {
            return iPage * iCount;
        }
        public void Init(string cookie,int pageCount=40) {
            strCookie = cookie;
            iCount = pageCount;
            string[] cookstr = cookie.Split(';');
            foreach (string str in cookstr)
            {
                //通过计算，解析skey值得到bkn特征值
                if (str.Trim().IndexOf("skey") == 0)
                {
                    string[] cookieNameValue = str.Split('=');
                    //以下算法从web js中获取，不同的qq登陆站点可能需要的参数并不一致
                    if (!string.IsNullOrEmpty(cookieNameValue[1]))
                    {
                        int t = 5381;
                        for (int r = 0, n = cookieNameValue[1].Length; r < n; ++r)
                        {
                            t += (t << 5) + (CharAt(cookieNameValue[1], r).ToCharArray()[0] & 0xff);
                        }
                        strBkn = (2147483647 & t).ToString();
                        break;
                    }
                }
            }
        }
        private string CharAt(string s, int index)
        {
            if ((index >= s.Length) || (index < 0))
                return "";
            return s.Substring(index, 1);
        }

        public async Task<List<GruopModel>> GetGroupModels() {
            string strUrl = "https://qun.qq.com/member.html";
            string strMsg = await HttpInfoHelper.GetResponseStringAsync(strUrl,
                               System.Net.Http.HttpMethod.Get, null);
            if (string.IsNullOrWhiteSpace(strMsg))
            {
                return null;
            }
            return Parse(strMsg);

        }

        public List<GruopModel> Parse(string strHtmlPage)
        {
            if (string.IsNullOrWhiteSpace(strHtmlPage))
            {
                return null;
            }
            string stxpath = "//div[@class='my-all-group']/ul[@class='my-group-list']/li";
            List<GruopModel> models = new List<GruopModel>();
            HtmlDocument htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(strHtmlPage);
            HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes(stxpath);
            if (nodes != null)
            {
                int iCount = nodes.Count;
                for (int i = 0; i < iCount; i++)
                {
                    HtmlNode item = nodes[i];

                    string strValue = item.InnerHtml;
                    string grpName = item.GetAttributeValue("title", "");
                    string grpCode = item.GetAttributeValue("data-id", "");
                    grpName = grpName.Replace("&amp;nbsp;"," ").Replace("&nbsp;"," ");
                    if (string.IsNullOrWhiteSpace(grpCode))
                    {
                        continue;
                    }
                    if (models.Where(x => x.Code == grpCode).Count() > 0)
                    {
                        continue;
                    }
                    string strImgUTL = "";
                    HtmlNode imgnode = item.SelectSingleNode("img");
                    if (imgnode != null)
                    {
                        strImgUTL = imgnode.GetAttributeValue("src", "");
                    }
                    GruopModel model = new GruopModel()
                    {
                        Code = grpCode,
                        Name = grpName,
                        ImgUrl = $"https:{strImgUTL}"
                    };
                    models.Add(model);
                }
            }
            return models;
        }
        public async Task<List<GroupMemberModel>> GetGroupMemberModels(string strGrpCode,int iPageIdx=1)
        {
            if (string.IsNullOrWhiteSpace(strGrpCode))
            {
                return null;
            }
            int iPageStart = iCount * (iPageIdx - 1);
            int iPageEnd = (iCount * iPageIdx)-1;
            string strUrl = string.Format("{4}?gc={0}&st={1}&end={2}&sort=0&bkn={3}", strGrpCode, iPageStart, iPageEnd, strBkn
                , "http://qun.qq.com/cgi-bin/qun_mgr/search_group_members");
            UriBuilder uriBuilder = new UriBuilder(strUrl);
            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, uriBuilder.Uri);
            req.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            req.Headers.Referrer = new Uri("http://qun.qq.com/member.html");
            string strMsg = await HttpInfoHelper.GetResponseStringAsync(req,
                               strCookie);
            if (string.IsNullOrWhiteSpace(strMsg))
            {
                return null;
            }
            JObject jos = null;
            try
            {
                jos = (JObject)JsonConvert.DeserializeObject<JObject>(strMsg);
            }
            catch (Exception)
            {
                return null;
            }
            if (jos == null) 
            {
                return null;
            }
            List<GroupMemberModel> groupMemberModels = new List<GroupMemberModel>();
            JArray array = jos["mems"] as JArray;
            if (array != null)
            {
                int ilength = array.Count;
                for (int i = 0; i < ilength; i++)
                {
                    JObject obj = (JObject)array[i];
                    GroupMemberModel groupMemberModel = new GroupMemberModel()
                    {
                        Code = obj["uin"].ToString(),
                        Card = obj["card"].ToString().Replace("&amp;nbsp;", " ").Replace("&nbsp;", " "),
                        Entertime =  
                            new DateTime(1970, 1, 1, 8, 0, 0).
                            AddSeconds((double)obj["join_time"]).ToString("yyyy/MM/dd"),
                        Lasttime = 
                            new DateTime(1970, 1, 1, 8, 0, 0).
                            AddSeconds((double)obj["last_speak_time"]).ToString("yyyy/MM/dd"),
                         Nick = obj["nick"].ToString().Replace("&amp;nbsp;", " ").Replace("&nbsp;", " "),
                         Ql = obj["qage"].ToString()+"年"
                    };
                    string strSexTag = obj["g"].ToString();
                    
                    if (strSexTag == "0")
                    {
                        groupMemberModel.Sex = "男";
                    }
                    else if (strSexTag == "1")
                    {
                        groupMemberModel.Sex = "女";
                    }
                    else if (strSexTag == "-1")
                    {
                        groupMemberModel.Sex = "未知";
                    }
                    groupMemberModels.Add(groupMemberModel);
                }
            }
            return groupMemberModels;
        }
    }
}
